package com.ihr360.job.core.item.support;

import com.ihr360.job.core.item.ItemReader;
import org.springframework.aop.support.AopUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * An {@link ItemReader} that pulls data from a list. Useful for testing.
 *
 * @author Dave Syer
 */
public class ListItemReader<T> implements ItemReader<T> {

    private List<T> list;

    public ListItemReader(List<T> list) {
        setList(list);
    }

    public ListItemReader() {
    }

    protected void setList(List<T> list) {
        // If it is a proxy we assume it knows how to deal with its own state.
        // (It's probably transaction aware.)
        if (AopUtils.isAopProxy(list)) {
            this.list = list;
        } else {
            this.list = new ArrayList<T>(list);
        }
    }

    @Override
    public T read() {
        if (!list.isEmpty()) {
            return list.remove(0);
        }
        return null;
    }

}
